<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>支付宝支付功能测试</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background: #f5f5f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
        }
        .header h1 {
            color: #333;
            margin-bottom: 10px;
        }
        .header p {
            color: #666;
            font-size: 14px;
        }
        .config-section {
            margin-bottom: 30px;
            padding: 20px;
            background: #f8f9fa;
            border-radius: 8px;
            border-left: 4px solid #1890ff;
        }
        .config-section h3 {
            margin-top: 0;
            color: #333;
        }
        .config-item {
            margin-bottom: 15px;
        }
        .config-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
            color: #333;
        }
        .config-item input {
            width: 100%;
            padding: 10px;
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            font-size: 14px;
        }
        .config-item input:focus {
            outline: none;
            border-color: #1890ff;
            box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
        }
        .test-section {
            margin-bottom: 30px;
        }
        .test-section h3 {
            color: #333;
            margin-bottom: 15px;
        }
        .test-button {
            background: #1890ff;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 6px;
            font-size: 16px;
            cursor: pointer;
            margin-right: 10px;
            margin-bottom: 10px;
        }
        .test-button:hover {
            background: #40a9ff;
        }
        .test-button:disabled {
            background: #d9d9d9;
            cursor: not-allowed;
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 6px;
            font-size: 14px;
        }
        .status.success {
            background: #f6ffed;
            border: 1px solid #b7eb8f;
            color: #52c41a;
        }
        .status.error {
            background: #fff2f0;
            border: 1px solid #ffccc7;
            color: #ff4d4f;
        }
        .status.info {
            background: #e6f7ff;
            border: 1px solid #91d5ff;
            color: #1890ff;
        }
        .log {
            background: #f5f5f5;
            border: 1px solid #d9d9d9;
            border-radius: 6px;
            padding: 15px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            max-height: 200px;
            overflow-y: auto;
            white-space: pre-wrap;
        }
        .public-key {
            background: #f0f0f0;
            padding: 10px;
            border-radius: 4px;
            font-family: 'Courier New', monospace;
            font-size: 12px;
            word-break: break-all;
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🔐 支付宝支付功能测试</h1>
            <p>测试真实支付宝支付集成功能</p>
        </div>

        <div class="config-section">
            <h3>📋 配置状态</h3>
            <div class="config-item">
                <label>支付宝公钥状态:</label>
                <div class="status success">✅ 已配置 (使用您提供的公钥)</div>
            </div>
            <div class="config-item">
                <label>公钥内容:</label>
                <div class="public-key">MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwGFZtwMX6eB+KnHQ39xFHa/w1h/wloyr86VNHyo5XcwVr0Tj2PqCfT9ja9sbk2YfSklcGXNYnceTD2eITIM3kr0N4hW2oS81gjnsSlrFwoML+VDzd5xHn6fcsjlR7ZTjvJdBxQo3f0PBl5bmQqPa1V2yGcvgPuzLkhKba32JYyiMjt6LiZQ3lN9c1axfDNyKCqm7+RxrqFvMjGUGQZXpsSo1KK14mOk7BcuRjI5oIDgVrRv9xmwsI8EVdZTOzUAhS+WO0OjUBcxZdUsmN7s/zoMbf4GVE3YZpERsDP14Gu5PBHlgtiV0b6gk3SgWP9sJxpBr/3JoHkrrzQ1U6JhdKQIDAQAB</div>
            </div>
        </div>

        <div class="config-section">
            <h3>⚙️ 需要配置的项目</h3>
            <div class="config-item">
                <label>应用ID (APP_ID):</label>
                <input type="text" id="appId" placeholder="请输入您的支付宝应用ID" />
            </div>
            <div class="config-item">
                <label>应用私钥 (PRIVATE_KEY):</label>
                <input type="text" id="privateKey" placeholder="请输入您的应用私钥" />
            </div>
        </div>

        <div class="test-section">
            <h3>🧪 功能测试</h3>
            <button class="test-button" onclick="testConfig()">测试配置</button>
            <button class="test-button" onclick="testCreateOrder()">测试创建订单</button>
            <button class="test-button" onclick="testPayment()">测试支付流程</button>
            <button class="test-button" onclick="testCallback()">测试回调处理</button>
            <button class="test-button" onclick="clearLog()">清空日志</button>
        </div>

        <div id="status"></div>
        <div class="log" id="log"></div>
    </div>

    <script>
        // 模拟支付宝支付服务
        class MockAlipayService {
            static log(message) {
                const logElement = document.getElementById('log');
                const timestamp = new Date().toLocaleTimeString();
                logElement.textContent += `[${timestamp}] ${message}\n`;
                logElement.scrollTop = logElement.scrollHeight;
            }

            static showStatus(message, type = 'info') {
                const statusElement = document.getElementById('status');
                statusElement.innerHTML = `<div class="status ${type}">${message}</div>`;
            }

            static async createOrder(orderData) {
                this.log('创建支付订单...');
                this.log(`订单数据: ${JSON.stringify(orderData, null, 2)}`);
                
                // 模拟API调用
                await new Promise(resolve => setTimeout(resolve, 1000));
                
                const mockResponse = {
                    success: true,
                    data: {
                        orderString: `alipay_sdk=alipay-sdk-node-4.0.0&app_id=${orderData.appId}&method=alipay.trade.app.pay&charset=UTF-8&sign_type=RSA2&timestamp=${new Date().toISOString()}&version=1.0&notify_url=${orderData.notifyUrl}&biz_content=${encodeURIComponent(JSON.stringify({
                            out_trade_no: orderData.orderNo,
                            total_amount: orderData.totalAmount,
                            subject: orderData.subject,
                            product_code: 'QUICK_MSECURITY_PAY'
                        }))}&sign=mock_sign`,
                        orderNo: orderData.orderNo
                    }
                };
                
                this.log('订单创建成功');
                return mockResponse;
            }

            static async pay(orderData) {
                this.log('发起支付宝支付...');
                
                const createResult = await this.createOrder(orderData);
                
                if (!createResult.success) {
                    return createResult;
                }

                this.log('检测支付环境...');
                
                // 检查是否在支付宝环境中
                if (window.AlipayJSBridge) {
                    this.log('检测到支付宝环境，使用APP内支付');
                    return new Promise((resolve) => {
                        window.AlipayJSBridge.call('tradePay', {
                            orderStr: createResult.data.orderString
                        }, (result) => {
                            this.log(`支付结果: ${JSON.stringify(result)}`);
                            if (result.resultCode === '9000') {
                                resolve({
                                    success: true,
                                    data: createResult.data
                                });
                            } else {
                                resolve({
                                    success: false,
                                    message: '支付失败'
                                });
                            }
                        });
                    });
                } else {
                    this.log('非支付宝环境，使用网页支付');
                    const payUrl = `alipays://platformapi/startapp?appId=${orderData.appId}&url=${encodeURIComponent(createResult.data.orderString)}`;
                    this.log(`支付URL: ${payUrl}`);
                    
                    // 模拟跳转
                    this.log('正在跳转到支付宝...');
                    return {
                        success: true,
                        data: createResult.data
                    };
                }
            }

            static handleCallback(callbackData) {
                this.log('处理支付回调...');
                this.log(`回调数据: ${JSON.stringify(callbackData, null, 2)}`);
                
                const isValidStatus = callbackData.trade_status === 'TRADE_SUCCESS' || 
                                   callbackData.trade_status === 'TRADE_FINISHED';
                
                if (!isValidStatus) {
                    this.log(`交易状态无效: ${callbackData.trade_status}`);
                    return false;
                }
                
                this.log('支付回调验证通过');
                return true;
            }
        }

        // 测试函数
        function testConfig() {
            MockAlipayService.log('=== 测试配置 ===');
            const appId = document.getElementById('appId').value;
            const privateKey = document.getElementById('privateKey').value;
            
            if (!appId) {
                MockAlipayService.showStatus('❌ 请配置应用ID', 'error');
                MockAlipayService.log('应用ID未配置');
                return;
            }
            
            if (!privateKey) {
                MockAlipayService.showStatus('❌ 请配置应用私钥', 'error');
                MockAlipayService.log('应用私钥未配置');
                return;
            }
            
            MockAlipayService.showStatus('✅ 配置验证通过', 'success');
            MockAlipayService.log('应用ID: ' + appId);
            MockAlipayService.log('私钥长度: ' + privateKey.length);
        }

        async function testCreateOrder() {
            MockAlipayService.log('=== 测试创建订单 ===');
            const appId = document.getElementById('appId').value;
            
            if (!appId) {
                MockAlipayService.showStatus('❌ 请先配置应用ID', 'error');
                return;
            }
            
            const orderData = {
                orderNo: 'TEST' + Date.now(),
                totalAmount: 0.01,
                subject: '测试订单',
                body: '这是一个测试订单',
                appId: appId,
                notifyUrl: '/api/alipay/notify',
                returnUrl: '/api/alipay/return'
            };
            
            try {
                const result = await MockAlipayService.createOrder(orderData);
                if (result.success) {
                    MockAlipayService.showStatus('✅ 订单创建成功', 'success');
                } else {
                    MockAlipayService.showStatus('❌ 订单创建失败', 'error');
                }
            } catch (error) {
                MockAlipayService.showStatus('❌ 订单创建异常: ' + error.message, 'error');
            }
        }

        async function testPayment() {
            MockAlipayService.log('=== 测试支付流程 ===');
            const appId = document.getElementById('appId').value;
            
            if (!appId) {
                MockAlipayService.showStatus('❌ 请先配置应用ID', 'error');
                return;
            }
            
            const orderData = {
                orderNo: 'TEST' + Date.now(),
                totalAmount: 0.01,
                subject: '测试支付',
                body: '这是一个测试支付',
                appId: appId,
                notifyUrl: '/api/alipay/notify',
                returnUrl: '/api/alipay/return'
            };
            
            try {
                const result = await MockAlipayService.pay(orderData);
                if (result.success) {
                    MockAlipayService.showStatus('✅ 支付发起成功', 'success');
                } else {
                    MockAlipayService.showStatus('❌ 支付发起失败: ' + result.message, 'error');
                }
            } catch (error) {
                MockAlipayService.showStatus('❌ 支付异常: ' + error.message, 'error');
            }
        }

        function testCallback() {
            MockAlipayService.log('=== 测试回调处理 ===');
            
            const mockCallbackData = {
                trade_no: '2024010122001234567890123456',
                out_trade_no: 'TEST' + Date.now(),
                trade_status: 'TRADE_SUCCESS',
                total_amount: '0.01',
                receipt_amount: '0.01',
                buyer_id: '2088001234567890',
                seller_id: '2088001234567890',
                gmt_payment: new Date().toISOString(),
                sign: 'mock_sign'
            };
            
            const isValid = MockAlipayService.handleCallback(mockCallbackData);
            if (isValid) {
                MockAlipayService.showStatus('✅ 回调处理成功', 'success');
            } else {
                MockAlipayService.showStatus('❌ 回调处理失败', 'error');
            }
        }

        function clearLog() {
            document.getElementById('log').textContent = '';
            document.getElementById('status').innerHTML = '';
        }

        // 页面加载完成后的初始化
        window.onload = function() {
            MockAlipayService.log('支付宝支付测试页面已加载');
            MockAlipayService.log('请配置应用ID和私钥后开始测试');
        };
    </script>
</body>
</html>

